package com.example.zjx8969.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class CountryUtil {

    public static String getCountry(Context context) {
        String country = getCountryFromLocation(context);
        if (!TextUtils.isEmpty(country)) {
            return country;
        }

        country = getCountryFromNetwork(context);
        if (!TextUtils.isEmpty(country)) {
            return country;
        }
        return getCountryFromLocale();
    }

    public static String getCountryFromLocation(Context context) {
        //没有权限认为获取失败
        if (!checkLocationPermissionEnable(context)) {
            return null;
        }
        Location recent = getMostRecentLocation(context);
        if (recent != null) {
            try {
                if (Geocoder.isPresent()) {
                    Geocoder geocoder = getGeocoder(context);
                    List<Address> addresses = geocoder.getFromLocation(recent.getLatitude(),
                            recent.getLongitude(), 1);
                    if (addresses != null) {
                        for (Address address : addresses) {
                            if (address != null) {
                                return address.getCountryCode();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                // Failed to reverse geocode location
            } catch (NullPointerException e) {
                // Failed to reverse geocode location
            } catch (NoSuchMethodError e) {
                // failed to fetch geocoder
            } catch (IllegalArgumentException e) {
                // Bad lat / lon values can cause Geocoder to throw IllegalArgumentExceptions
            } catch (IllegalStateException e) {
                // sometimes the location manager is unavailable
            }
        }
        return null;
    }


    private static boolean checkLocationPermissionEnable(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                ;
    }

    private static Geocoder getGeocoder(Context context) {
        return new Geocoder(context, Locale.ENGLISH);
    }


    private static Location getMostRecentLocation(Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        // Don't crash if the device does not have location services.
        if (locationManager == null) {
            return null;
        }

        // It's possible that the location service is running out of process
        // and the remote getProviders call fails. Handle null provider lists.
        List<String> providers = null;
        try {
            providers = locationManager.getProviders(true);
        } catch (SecurityException e) {
            // failed to get providers list
        }
        if (providers == null) {
            return null;
        }

        List<Location> locations = new ArrayList<Location>();
        for (String provider : providers) {
            Location location = null;
            try {
                //主工程已经注册权限
                location = locationManager.getLastKnownLocation(provider);
            } catch (IllegalArgumentException e) {
                // failed to get last known location from provider
            } catch (SecurityException e) {
                // failed to get last known location from provider
            }
            if (location != null) {
                locations.add(location);
            }
        }

        long maximumTimestamp = -1;
        Location bestLocation = null;
        for (Location location : locations) {
            if (location.getTime() > maximumTimestamp) {
                maximumTimestamp = location.getTime();
                bestLocation = location;
            }
        }

        return bestLocation;
    }

    public static String getCountryFromNetwork(Context context) {
        //提供接口供QA修改本地net work country
/*        String debugCountry = PreferenceUtil.getString(context, DevicePref.FILE_DEVICE_CONFIG,
                DevicePref.KEY_LAST_COUNTRY, "");
        if (!TextUtils.isEmpty(debugCountry)) {
            return debugCountry;
        }*/


        try {
            TelephonyManager manager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (manager != null && manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
                String country = manager.getNetworkCountryIso();
                if (country != null && country.length() == 2) {
                    return country.toLowerCase(Locale.US);
                }
            }
        } catch (Exception e) {
            // Failed to get country from network
        }
        return null;
    }

    public static String getCountryFromLocale() {
        return Locale.getDefault().getCountry();
    }
}
